package com.example.ddz.framework;

/**
 * Created by IntelliJ IDEA.
 * User: Marcel Melzig
 * Date: 10.08.11
 * Time: 21:39
 */

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Manages the rendering of the game views.
 */
public class AndroidFastRenderView extends SurfaceView implements Runnable
{
    private final AndroidGame game;
    private final Bitmap framebuffer;
    private Thread renderThread = null;
    private final SurfaceHolder holder;
    private volatile boolean running = false;

    /**
     * Creates am instance of the render view.
     *
     * @param game        The game activity.
     * @param framebuffer The framebuffer.
     */
    public AndroidFastRenderView(AndroidGame game, Bitmap framebuffer)
    {
        super(game);
        this.game = game;
        this.framebuffer = framebuffer;
        this.holder = getHolder();
    }

    /**
     * Resumes the thread.
     */
    public void Resume()
    {
        running = true;
        renderThread = new Thread(this);
        renderThread.start();
    }

    /**
     * Runs the render thread.
     */
    public void run()
    {
        Rect dstRect = new Rect();
        long startTime = System.nanoTime();
        while (running)
        {
            if (!holder.getSurface().isValid())
                continue;
            float deltaTime = (System.nanoTime() - startTime) / 1000000000.0f;
            startTime = System.nanoTime();
            game.GetCurrentScreen().Update(deltaTime);
            game.GetCurrentScreen().Present(deltaTime);
            Canvas canvas = holder.lockCanvas();
            canvas.getClipBounds(dstRect);
            canvas.drawBitmap(framebuffer, null, dstRect, null);
            holder.unlockCanvasAndPost(canvas);
        }
    }

    /**
     * Pauses the thread.
     */
    public void Pause()
    {
        running = false;
        while (true)
        {
            try
            {
                renderThread.join();
                break;
            }
            catch (InterruptedException e)
            {
                // retry
            }
        }
    }
}

